﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Navigation;

namespace Elca.MvvmHelpers {

    public class NavigateHelper {

        private readonly static List<FrameworkElement> s_knownElements = new List<FrameworkElement>();

        public static readonly DependencyProperty IsNavigationAutomaticProperty =
                DependencyProperty.RegisterAttached(
                        "IsNavigationAutomatic", typeof (bool), typeof (NavigateHelper),
                        new UIPropertyMetadata(false, OnIsNavigationAutomaticPropertyChanged));


        public static bool GetIsNavigationAutomatic(Hyperlink obj) {
            return (bool) obj.GetValue(IsNavigationAutomaticProperty);
        }

        public static void SetIsNavigationAutomatic(Hyperlink obj, bool value) {
            obj.SetValue(IsNavigationAutomaticProperty, value);
        }

        private static void OnIsNavigationAutomaticPropertyChanged(DependencyObject d,
                                                       DependencyPropertyChangedEventArgs e) {
            var hl = d as Hyperlink;
            if (hl == null) {
                return;
            }

            if ((bool) e.NewValue) {

                HookHandlers(hl);
            } else {
                UnhookHandlers(hl);
            }
        }

        private static void HookHandlers(Hyperlink hl) {
            hl.Unloaded += OnUnloaded;
            hl.Loaded += OnLoaded;
            hl.RequestNavigate += OnRequestNavigate;
        }

        private static void UnhookHandlers(Hyperlink hl) {
            hl.Unloaded -= OnUnloaded;
            hl.Loaded -= OnLoaded;
            hl.RequestNavigate -= OnRequestNavigate;
        }

        private static void OnRequestNavigate(object sender, RequestNavigateEventArgs e) {

            LaunchBrowser(e.Uri);
        }

        private static void OnUnloaded(object sender, RoutedEventArgs e) {
            Hyperlink hl = (Hyperlink)sender;
            UnhookHandlers(hl);
        }

        private static void OnLoaded(object sender, RoutedEventArgs e) {
            Hyperlink hl = (Hyperlink)sender;
            hl.ToolTip = hl.NavigateUri.ToString();
        }

        private static void LaunchBrowser(Uri uri) {

            Process.Start(uri.ToString());
        }
    }
}
